package codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import support.RpcInfo;
import support.TcpProto;
import util.SerializeTool;

public class DataEncode extends MessageToByteEncoder<RpcInfo> {

    static Logger logger = LoggerFactory.getLogger(DataEncode.class);

    @Override
    protected void encode(ChannelHandlerContext ctx, RpcInfo msg, ByteBuf out) throws Exception {
        try { //如果编码器发生异常，netty不会向上抛出，而是自己处理了，导致这次发送无效，若出现这种情况，这里也要发出去，所以自己捕获处理
            byte[] bytes= SerializeTool.object2Byte(msg);
            TcpProto tcpProto = new TcpProto(bytes, bytes.length);
            logger.info("编码成功,字节长度:{}...",bytes.length);

            out.writeLong(bytes.length);
            out.writeBytes(bytes);
        }catch (Exception e){
            RpcInfo ex = new RpcInfo();
            ex.setErrorCode(e.toString());
            byte[] bytes = SerializeTool.object2Byte(ex);
            logger.error("编码失败,把错误信息编码重新返回，错误信息字节长度:{}...",bytes.length);

            out.writeLong(bytes.length);
            out.writeBytes(bytes);
        }

    }
}
